<template>
  <el-scrollbar class="test-log">
    <div v-if="Array.isArray(logList) && logList.length" class="list">
      <DynamicScroller v-if="logList && logList.length" style="height: 100%; overflow: auto" :items="logList"
        key-field="id" :min-item-size="30" @scroll-end="scrollEnd">
        <template #default="{ item, index, active }">
          <DynamicScrollerItem v-if="item" :item="item" :active="active" :data-index="index">
            <div class="item">
              <div class="time">{{ item.time }}</div>
              <div class="summary">{{ item.summary }}</div>
            </div>
          </DynamicScrollerItem>
        </template>
      </DynamicScroller>
    </div>
    <Empty v-else :props="{ imageSize: 80 }" />
  </el-scrollbar>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { getTestLogsByPage } from "../../api/test/index";
import type { TestLogsItem } from "../../api/test/index.d";
import { onMounted } from "vue";
const query = ref({ pageIndex: 1, pageSize: 100 });
const logList = ref<TestLogsItem[]>([]);
const total = ref(0);
import { useTestStore } from "../../store/testStore";
const testStore = useTestStore();

onMounted(() => {
  getTestLog();
});
const getTestLog = async () => {
  console.log("准备获取日志列表");
  try {
    const result = await getTestLogsByPage(query.value, { taskId: testStore.taskId || "" });
    console.log("获取日志列表成功", result);
    console.log("logList值:", logList.value);

    // 安全地解构数据
    const data = result?.data || {};
    const list = data?.list || [];
    const total_Count = data?.total_Count || 0;

    logList.value = [...logList.value, ...list];
    total.value = total_Count;
  } catch (error) {
    console.error("获取日志列表失败", error);
    logList.value = [];
    total.value = 0;
  }
};
const setTestLog = (log: TestLogsItem) => {
  logList.value.push({ ...log, id: String(+new Date()) });
};
const clearTestLog = () => {
  logList.value = [];
};
const scrollEnd = () => {
  if (logList.value.length < total.value) {
    console.log("滚动到最底部");
    query.value.pageIndex++;
    getTestLog();
  }
};
defineExpose({ setTestLog, clearTestLog });
</script>

<style lang="scss" scoped>
.test-log {
  height: calc(100% - 20px);
  padding: 10px;

  :deep(.el-scrollbar__view) {
    height: 100%;
  }

  .list {
    height: 100%;

    .item {
      display: flex;
      position: relative;
      padding-bottom: 12px;
      line-height: 18px;

      .time {
        color: #666;
        margin-right: 10px;
        white-space: nowrap;
      }
    }
  }
}
</style>
